package com.web.base.core.provider;

import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.core.cache.AreaCache;
import com.web.base.core.exception.AreaException;
import com.web.base.core.facade.AreaFacade;
import com.web.base.core.message.AreaRequest;
import com.web.base.core.message.AreaResponse;
import com.web.base.core.model.Area;
import com.web.base.core.service.AreaService;
import com.web.base.core.util.AreaConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 区域接口实现类
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2018年06月19日
 */
@Component("coreAreaProvider")
public class AreaProvider implements AreaFacade
{
	@Autowired
	private AreaService areaService;
	@Autowired
	private AreaCache areaCache;
	
	public AreaProvider()
	{
	}

	@Override
	public AreaResponse add(AreaRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Area area = AreaConvertor.toArea(request);
		area = areaService.save(area);
		areaCache.delete();
		AreaResponse response = AreaConvertor.toResponse(area);
		return response;
	}

	@Override
	public AreaResponse update(AreaRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Area area = AreaConvertor.toArea(request);
		area = areaService.save(area);
		areaCache.delete();
		AreaResponse response = AreaConvertor.toResponse(area);
		return response;
	}

	@Override
	public AreaResponse get(Integer id)
	{
		if (id == null)
			throw new AreaException("Id不能为空");
			
		Area area = areaCache.get(id);
		AreaResponse response = AreaConvertor.toResponse(area);
		return response;
	}

	@Override
	public Map<Integer, AreaResponse> getList(Collection<Integer> idList)
	{
		Map<Integer, Area> map = areaCache.getList(idList);
		Map<Integer, AreaResponse> responseMap = AreaConvertor.toAreaResponse(map);
		return responseMap;
	}

	@Override
	public Map<Integer, String> getNameList(Collection<Integer> idList)
	{
		Map<Integer, String> map = areaCache.getNameList(idList);
		return map;
	}

	@Override
	public Map<String, List<AreaResponse>> listTree(AreaRequest request)
	{
		Area area = AreaConvertor.toArea(request);
		Map<String, List<Area>> tree = areaService.listTree(area);
		Map<String, List<AreaResponse>> treeResponse = AreaConvertor.toResponse(tree);
		return treeResponse;
	}

	@Override
	public void refresh()
	{
		areaCache.delete();
	}

}
